# Convert "My Clippings.txt" in Kindle to markdown or html format

import getopt
import sys
from docx import Document

# 获取命令行参数
opts, args = getopt.getopt(sys.argv[1:], "-h-p-i:-o:")

# 默认不输出位置和时间
export_position_time = False

for opt_name, opt_value in opts:
    if opt_name in ('-i'):
        in_clippings = opt_value
    elif opt_name in ('-o'):
        out_clippings = opt_value
    elif opt_name in ('-p'):
        export_position_time = True

# 根据后缀判断输出格式
out_clippings_format = out_clippings.split('.')[-1]

# Kindle的My Clippings.txt中每条文摘以“==========”分割
clippings = open(in_clippings, 'r').read().split('==========\n')

#默认标题
title = 'My Clippings'

# 以字典存文摘，书名为索引
clip_out = {}

# 最后一个clipping为空
for i in clippings[:-1]:
    clip = i.strip().split('\n')
    book = clip[0].strip()
    position_time = clip[1].strip().split('|')
    position = position_time[0].strip()
    time = position_time[1].strip()
    time_position = time+' '+position
    note = '\n'.join(clip[2:]).strip()

    # 以书名为索引存入字典
    try:
        clip_out[book][time_position] = note
    # 若书名不存在，新建书名字典
    except:
        clip_out[book] = dict()
        clip_out[book][time_position] = note

# 根据后缀输出不同格式
if out_clippings_format == 'docx':
    # 输出docx格式
    document = Document('zh-template.docx')
    document.add_heading(title, level = 0)
    for k in clip_out.keys():
        document.add_heading(k, level = 1)
        for kk in clip_out[k].keys():
            if export_position_time:
                document.add_paragraph(kk)
                document.add_paragraph(clip_out[k][kk])
            else:
                document.add_paragraph(clip_out[k][kk])
    document.save(out_clippings)
else:
    # 若非docx，输出markdown格式
    with open('%s.md' %out_clippings, 'w') as out_md:
        out_md.write('---\ntitle: %s\n---\n\n' %title)
        for k in clip_out.keys():
            out_md.write('# %s\n\n' %k)
            for kk in clip_out[k].keys():
                if export_position_time:
                    out_md.write('%s\n\n>%s\n\n' %(kk, clip_out[k][kk]))
                else:
                    out_md.write('>%s\n\n' %(clip_out[k][kk]))
